<template>
  <div :id="withKeyId" class="mars3d-container"></div>
  <div class="test">
    <tree-component @add-graphic-layer="addGraphicLayer" @remove-graphic-layer="removeGraphicLayer" />
  </div>
  <div class="test2">
    <table-component @add-graphic-layer="addGraphicLayer" @remove-graphic-layer="removeGraphicLayer" />
  </div>
</template>
<script setup lang="ts">

import { computed, onUnmounted, onMounted,ref } from "vue"
import * as mars3d from "mars3d" 
// import { $alert, $message } from "@mars/components/mars-ui/index"

import {mapOptions} from "../../script/config"
import {
  areasData
} from "../../script/data"
import {createGraphicEffect,createGraphicLine} from"../../script/graphicLayer"
import {
  load3DTileMapConfig,load3DTileLayer,
} from "../../script/3dTileLayerConfig"

import TreeComponent from "../TreeComponent.vue"
import TableComponent from "../TableComponent.vue"



let graphicData: Record<string, mars3d.graphic> = {};
// 传递至其他组件中调用的函数
const addGraphicLayer = (name:string) => {
  // console.log("The function addGraphicLayer has been used.");
  console.log("所选目录为：",name);

  if(graphicLayer){
    
      let data = areasData[name];
      console.log("data:",data);
      let showAttr: Record<string, any> = {};
      showAttr["空域名称"] = areasData[name]["name"];
      showAttr["空域半径"] = areasData[name]["radius"];
      showAttr["空域中心点"] = `经度：${areasData[name]["longtitude"]},纬度：${areasData[name]["latitude"]},高度：${areasData[name]["altitude"]}`;


      let graphic = createAllowArea(data,graphicLayer);


      graphic.attr = showAttr;

      graphicData[name] = graphic;
      graphicLayer.addGraphic(graphic);
      // FIXME:flyTo没处理好
      // graphicLayer.flyTo(
      //   graphic, {
      //   heading: 1,       // 设置方向为 1 度
      //   pitch: -80,       // 设置俯仰角为 -80 度
      //   range: 1000,      // 设置视距，可根据需求调整
      //   duration: 3       // 设置飞行时间（秒），可以根据需要调整
      // });

    

  }


};
function createAllowArea(data:any,graphicLayer:mars3d.layer.GraphicLayer){
  let centerPos = new mars3d.LngLatPoint(data.longtitude,data.latitude,data.altitude);
  let graphic =  createGraphicEffect(centerPos,data.radius,data.color);//createGraphicLine

  return graphic;
}

const removeGraphicLayer = (name:string)=>{
  console.log("取消勾选目录为：",name);

  if(graphicLayer){
    if(graphicData[name])
      graphicLayer.removeGraphic(graphicData[name]);
    else{
      console.log("graphicData中不存在该目录");
    }
      
  }

}


// 获取App.vue中的用户定义的map-key
const props = withDefaults(
  defineProps<{
    mapKey?: string
    options?: any
  }>(),
  {
    mapKey: "default",
    options: () => ({})
  }
);

// 用于存放地球组件实例
let map: mars3d.Map // 地图对象

// 使用用户传入的 mapKey 拼接生成 withKeyId 作为当前显示容器的id
const withKeyId = computed(() => `mars3d-container-${props.mapKey}`)


onMounted(() => {
  // 获取配置并初始化地图
  initMars3d(mapOptions);

})

// onload事件将在地图渲染后触发
const emit = defineEmits(["onload"])
const initMars3d = (option: any) => {
  map = new mars3d.Map(withKeyId.value, option);

  // 开场动画
  // map.openFlyAnimation();

  // 针对不同终端的优化配置
  if (mars3d.Util.isPCBroswer()) {
    map.zoomFactor = 2.0 // 鼠标滚轮放大的步长参数

    // IE浏览器优化
    if (window.navigator.userAgent.toLowerCase().indexOf("msie") >= 0) {
      map.viewer.targetFrameRate = 20 // 限制帧率
      map.scene.requestRenderMode = false // 取消实时渲染
    }
  } else {
    map.zoomFactor = 5.0 // 鼠标滚轮放大的步长参数

    // 移动设备上禁掉以下几个选项，可以相对更加流畅
    map.scene.requestRenderMode = false // 取消实时渲染
    map.scene.fog.enabled = false
    map.scene.skyAtmosphere.show = false
    map.scene.globe.showGroundAtmosphere = false
  }

  // //二三维切换不用动画
  if (map.viewer.sceneModePicker) {
    map.viewer.sceneModePicker.viewModel.duration = 0.0
  }

  // webgl渲染失败后，刷新页面
  // map.on(mars3d.EventType.renderError, async () => {
  //   await $alert("程序内存消耗过大，请重启浏览器")
  //   window.location.reload()
  // })

  map.toolbar.style.bottom = "120px" // 修改toolbar控件的样式

  // 方式2：在创建地球后按需调用addControl添加(直接new对应type类型的控件)
  const locationBar = new mars3d.control.LocationBar({
    fps: true,
    template:
      "<div>经度:{lng}</div> <div>纬度:{lat}</div> <div>海拔：{alt}米</div> <div>层级：{level}</div><div>方向：{heading}度</div> <div>俯仰角：{pitch}度</div><div>视高：{cameraHeight}米</div>"
  })
  map.addControl(locationBar)

  // 右键菜单
  bindMapDemo();

  console.log("地图上已有控件", map.control)
  // 展示版权信息
  addCreditDOM();

  // 添加蓝色滤镜
  addFilterTileLayer(map);

  // 设置鼠标操作习惯,更换中键和右键
  map.changeMouseModel(true);




  // map构造完成后的一些处理
  onMapLoad();

  emit("onload", map);
}

let graphicLayer:mars3d.layer.GraphicLayer | null;
// map构造完成后的一些处理
function onMapLoad() {
  // 初始化矢量数据图层
  graphicLayer = new mars3d.layer.GraphicLayer();
  map.addLayer(graphicLayer);
 
  // 在layer上绑定监听事件
  graphicLayer.on(mars3d.EventType.click, function (event) {
    console.log("监听layer，单击了矢量对象", event);

  });
  bindLayerPopup(); // 在图层上绑定popup,对所有加到这个图层的矢量数据都生效
 
  // 加载3DTile数据
  load3DTileMapConfig(map);

  const baimoURL = "http://127.0.0.1:8080/tileset.json";
  // console.log("3dtile data:",baimoURL);
  const popup = [
    { field: "OBJECTID", name: "编号" },
    { field: "name", name: "名称" },
    { field: "height", name: "楼高", unit: "米" }
  ];
  let tilesetLayer = load3DTileLayer("武汉市白模",baimoURL,popup);
  // map.addLayer(tilesetLayer);


  // map.basemap = "高德电子";
}

// 叠加的图层
let tileLayer:mars3d.layer.GaodeLayer | null;
function addFilterTileLayer(map:mars3d.Map) {
  removeFilterTileLayer();
  // 创建滤镜图层
  tileLayer = new mars3d.layer.GaodeLayer({
    layer: "vec",
    invertColor: true, // 反向颜色 color.r = 1.0 - color.r
    filterColor: "#4e70a6", // 滤镜颜色  color.r = color.r * filterColor.r
    brightness: 0.6,
    contrast: 1.8,
    gamma: 0.3,
    hue: 1,
    saturation: 0
  });
  map.addLayer(tileLayer);

}

function removeFilterTileLayer() {
  if (tileLayer) {
    map?.removeLayer(tileLayer, true);
    tileLayer = null;
  }
}

// 在图层绑定Popup弹窗
function bindLayerPopup() {
  if(graphicLayer){
    graphicLayer?.bindPopup(function (event) {

      console.log("bindPopup", event);
      const attr = event.graphic.attr || {} ;

      return mars3d.Util.getTemplateHtml({ title: "空域信息", template: "all", attr });
    });
  }
  else{
    console.error("graphicLayer is null.");
  }

}


// 在map地图上绑定右键菜单
function bindMapDemo() {

const mapContextmenuItems = [
  {
    text: "显示此处经纬度",
    icon: `<svg class="iconsvg" aria-hidden="true">
            <use xlink:href="#marsgis-qjsjdb"></use>
          </svg>`, // 支持iconfont的symbol方式图标（svg）
    show: (e) =>{
      return Cesium.defined(e.cartesian);
    },
    callback: (e)=>{
      const mpt = mars3d.LngLatPoint.fromCartesian(e.cartesian);
      console.log(mpt.toString(), "位置信息");
    }
  },
  {
    text: "查看当前视角",
    // icon: "fa fa-camera-retro", // 支持 font-class 的字体方式图标
    callback: (e) => {
      const mpt = JSON.stringify(map?.getCameraView());
      console.log(mpt, "当前视角信息");
    }
  },
  {
    text: "开启深度监测",
    // icon: "//data.mars3d.cn/img/marker/square.png", // 支持base64或url图片
    show: function () {
      return !map?.scene.globe.depthTestAgainstTerrain;
    },
    callback: (e) => {
      map.scene.globe.depthTestAgainstTerrain = true;
    }
  },
  {
    text: "关闭深度监测",
    // icon: "fa fa-eye",
    show: function () {
      return map?.scene.globe.depthTestAgainstTerrain;
    },
    callback: (e) => {
      map.scene.globe.depthTestAgainstTerrain = false;
    }
  },
];
map?.bindContextMenu(mapContextmenuItems);

setTimeout(() => {
  map?.openContextMenu(new mars3d.LngLatPoint(116.318747, 31.044486, 651.9))
}, 5000);
}

// 在下侧状态栏增加一个额外div展示图层版权信息
let creditDOM: any | null=null;
function addCreditDOM() {
  const locationBar = map?.control.locationBar?.container;
  // console.log("locationBar",locationBar);

  if (locationBar) {
    creditDOM = mars3d.DomUtil.create("div", "mars3d-locationbar-content mars3d-locationbar-autohide", locationBar)
    creditDOM.style["pointer-events"] = "all"
    creditDOM.style.float = "left"
    creditDOM.style.marginLeft = "20px"

    creditDOM.innerHTML = map?.basemap?.options?.credit || ""

    map?.on(mars3d.EventType.changeBasemap, function (event) {
      creditDOM.innerHTML = event.layer?.options?.credit || ""
    })
  }
  else{
    console.log("map.control.locationBar is null.");
  }
}
function removeCreditDOM() {
  if (creditDOM) {
    mars3d.DomUtil.remove(creditDOM)
    creditDOM = null
  }
}

// 组件卸载之前销毁mars3d实例
onUnmounted(() => {
  removeCreditDOM();

  removeFilterTileLayer();

  if (map) {
    map.destroy()
    map = null
  }
  console.log("map销毁完成", map)
})
</script>

<style lang="less"> 
.test{
  z-index: 999;
  position: absolute;
  left: 10px;
  top: 10px;
  background: rgba(0, 138, 255, 0.2);
  // TODO：根据内容自适应大小
  display: inline-block;
  width: auto;
  height: auto;
  overflow-wrap: break-word;
  display: none;//隐藏目录树
}
.test2{
  z-index: 999;
  position: absolute;
  right: 10px;
  top: 10px;
  background: rgba(0, 138, 255, 0.2);
  display: inline-block;
  width: auto;
  height: auto;
  overflow-wrap: break-word;
}




/**cesium 工具按钮栏*/
.cesium-viewer-toolbar {
  top: auto !important;
  bottom: 35px !important;
  left: 12px !important;
  right: auto !important;
}
.cesium-toolbar-button img {
  height: 100%;
}
.cesium-viewer-toolbar > .cesium-toolbar-button,
.cesium-navigationHelpButton-wrapper,
.cesium-viewer-geocoderContainer {
  margin-bottom: 5px;
  float: left;
  clear: both;
  text-align: center;
}
.cesium-button {
  background-color: rgba(23, 49, 71, 0.8);
  color: #e6e6e6;
  fill: #e6e6e6;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
  line-height: 32px;
}
.cesium-button:hover {
  background: #3ea6ff;
}

/**cesium 底图切换面板*/
.cesium-baseLayerPicker-dropDown {
  bottom: 0;
  left: 40px;
  max-height: 700px;
  margin-bottom: 5px;
  background-color: rgba(23, 49, 71, 0.8);
}

/**cesium 帮助面板*/
.cesium-navigation-help {
  top: auto;
  bottom: 0;
  left: 40px;
  transform-origin: left bottom;
  background: none;
  background-color: rgba(23, 49, 71, 0.8);
  .cesium-navigation-help-instructions {
    background: none;
  }
  .cesium-navigation-button {
    background: none;
  }
  .cesium-navigation-button-selected,
  .cesium-navigation-button-unselected:hover {
    background: rgba(0, 138, 255, 0.2);
  }
}

/**cesium 二维三维切换*/
.cesium-sceneModePicker-wrapper {
  width: auto;
}
.cesium-sceneModePicker-wrapper .cesium-sceneModePicker-dropDown-icon {
  float: right;
  margin: 0 3px;
}

/**cesium POI查询输入框*/
.cesium-viewer-geocoderContainer .search-results {
  left: 0;
  right: 40px;
  width: auto;
  z-index: 9999;
}
.cesium-geocoder-searchButton {
  background-color: rgba(23, 49, 71, 0.8);
}
.cesium-viewer-geocoderContainer .cesium-geocoder-input {
  background-color: rgba(63, 72, 84, 0.7);
}
.cesium-viewer-geocoderContainer .cesium-geocoder-input:focus {
  background-color: rgba(63, 72, 84, 0.9);
}
.cesium-viewer-geocoderContainer .search-results {
  background-color: rgba(23, 49, 71, 0.8);
}

/**cesium info信息框*/
.cesium-infoBox {
  top: 50px;
  background-color: rgba(23, 49, 71, 0.8);
}
.cesium-infoBox-title {
  background-color: rgba(23, 49, 71, 0.8);
}

/**cesium 任务栏的FPS信息*/
.cesium-performanceDisplay-defaultContainer {
  top: auto;
  bottom: 35px;
  right: 50px;
}
.cesium-performanceDisplay-ms,
.cesium-performanceDisplay-fps {
  color: #fff;
}

/**cesium tileset调试信息面板*/
.cesium-viewer-cesiumInspectorContainer {
  top: 10px;
  left: 10px;
  right: auto;
}
.cesium-cesiumInspector {
  background-color: rgba(23, 49, 71, 0.8);
}

/**覆盖mars3d内部控件的颜色等样式*/
.mars3d-compass .mars3d-compass-outer {
  fill: rgba(23, 49, 71, 0.8);
}
.mars3d-contextmenu-ul,
.mars3d-sub-menu {
  background-color: rgba(23, 49, 71, 0.8);

  > li > a:hover,
  > li > a:focus,
  > li > .active {
    background-color: #3ea6ff;
  }

  > .active > a,
  > .active > a:hover,
  > .active > a:focus {
    background-color: #3ea6ff;
  }
}

/* Popup样式*/
.mars3d-popup-color {
  color: #ffffff;
}
.mars3d-popup-background {
  background: rgba(23, 49, 71, 0.8);
}
.mars3d-popup-content {
  margin: 15px;
}
.mars3d-template-content label {
  padding-right: 6px;
}
.mars3d-template-titile {
  border-bottom: 1px solid #3ea6ff;
}
.mars3d-template-titile a {
  font-size: 16px;
}
.mars3d-tooltip {
  background: rgba(23, 49, 71, 0.8);
  border: 1px solid rgba(23, 49, 71, 0.8);
}

.mars3d-popup-btn-custom {
  padding: 3px 10px;
  border: 1px solid #209ffd;
  background: #209ffd1c;
}
</style>
